<?php declare(strict_types=1);


namespace App\Listener;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Consul\Agent;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Log\Helper\CLog;
use Swoft\Server\ServerEvent;
use Swoft\Server\Swoole\SwooleEvent;

/**
 * Class RegisterServer
 * @package App\Listener
 * @Listener(SwooleEvent::START)
 */

class RegisterServer implements EventHandlerInterface
{

    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;


    /**
     * 独立的事件监听器接口，在服务启动前注册服务
     * @param EventInterface $event
     */
    public function handle(EventInterface $event) : void
    {
//        //注册consul服务
//        var_dump('服务启动前consul服务中注册服务');
//        //获取consul配置信息
//        $config = bean('config')->get('provider.consul');
//        //注册consul配置
//        bean('consulProvider')->registerServer($config);

        sgo(function (){
            $service = [
                'ID'                => 'notify',
                'Name'              => 'notify_1',
                'Tags'              => [
                    'notify'
                ],
                'Address'           => '192.168.2.251',
                'Port'              => 9505,
                'Check'             => [ //指定检查服务状态的相关参数
                    'tcp'      => '192.168.2.251:9505',  //http形式的请求
                    'interval' => '5s', //检查时间
                    'timeout'  => '2s',
                ],
                'Meta'              => [
                    'version' => '1.0'
                ],
                'EnableTagOverride' => false,
                'Weights'           => [
                    'Passing' => 10,
                    'Warning' => 1
                ]
            ];

            // Register
            $this->agent->registerService($service);
            CLog::info('Swoft http register service success by consul!');
        });

    }
}